package com.example.douyin.config;

import cn.hutool.core.map.MapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.Map;

/**
 * 全局异常处理配置
 *
 * @ControllerAdvice使用这个 Controller ，可以实现三个方面的功能：全局异常处理、全局数据绑定、全局数据预处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandleConfig {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandleConfig.class);

    /**
     * 顶级异常处理
     * <p>
     * RestResultVo 为返回结果的通用实体
     */
    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e) {
        //annotation抛出的异常
        if (e instanceof UndeclaredThrowableException) {
            e = (Exception) ((UndeclaredThrowableException) e).getUndeclaredThrowable();
        }
        log.error("[handleException]: ", e);
        Map<Object, Object> RES = MapUtil.newHashMap();
        RES.putIfAbsent("code", 800);
        RES.putIfAbsent("message", e.getMessage());
        return RES;
    }

}